"ui";

importClass(Packages.androidx.recyclerview.widget.RecyclerView);
importClass(Packages.androidx.recyclerview.widget.LinearLayoutManager);
importClass(android.graphics.Color);
importClass(Packages.androidx.swiperefreshlayout.widget.SwipeRefreshLayout);
importClass(android.view.View);

let yashuUtil = require("./yashuUtil");
let service = require("./service");
let config = require("./config");
require("./component/data-show");
let baseUrl = config.baseUrl;
let themeColor = config.themeColor;
let status_bar_height = yashuUtil.status_bar_height;
let materialColors = config.materialColors;
ui.layout(
  <vertical bg="{{themeColor}}" paddingTop="{{status_bar_height}}px" gravity="center" padding="16">
    <horizontal>
      <input
        layout_weight="1"
        gravity="center"
        textSize="16sp"
        id="repoName"
        textColor="#ffffff"
        hint="仓库名字"
      ></input>
      <button id="search" text="搜索" textColor="#ffffff" />
    </horizontal>
    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
      id="swipeRefreshLayout"
      layout_width="match_parent"
      layout_height="wrap_content"
    >
      <androidx.recyclerview.widget.RecyclerView
        id="recyclerView"
        layout_width="match_parent"
        layout_height="match_parent"
      />
    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
  </vertical>
);
ui.search.click(function () {
  let repoName = ui.repoName.text().trim();
  if (!repoName) {
    {
      toastLog("请输入仓库名字");
      return;
    }
  }

  ui.swipeRefreshLayout.setEnabled(true);
  let token = service.readToken();
  let url =
    baseUrl +
    "/search/repositories?access_token=" +
    token +
    "&q=" +
    repoName +
    "&page=1&per_page=" +
    config.searchResultCount +
    "&order=desc";
  ui.swipeRefreshLayout.setRefreshing(true);
  http.get(url, {}, function (res, err) {
    ui.run(function () {
      ui.swipeRefreshLayout.setRefreshing(false);
      ui.swipeRefreshLayout.setEnabled(false);
    });
    if (err) {
      console.error(err);
      return;
    }
    if (res.statusCode !== 200) {
      toastLog("搜索仓库异常");
    } else {
      let items = res.body.json();
      var len = items.length;
      for (var i = 0; i < len; i++) {
        let item = items[i];
        item.color = materialColors[i % materialColors.length];
        item.repoUrl = item.html_url.replace(".git", "");
      }
      toastLog("搜索成功");
      ui.run(function () {
        // 设置布局管理器
        ui.run(function () {
          let layoutManager = new LinearLayoutManager(context);
          ui.recyclerView.setLayoutManager(layoutManager);
          let recycleAdapter = createRecyclerViewAdapter(items);
          ui.recyclerView.setAdapter(recycleAdapter);
        });
      });
    }
  });
});
yashuUtil.setStatusBarFullTransparent();
yashuUtil.setBackgroundRoundGradientCornerRadii(ui.repoName, "#229c27b0");
yashuUtil.setBackgroundRoundGradientCornerRadiiButton(ui.search, "#1fa62b");
ui.repoName.setHintTextColor(colors.parseColor("#b3ffffff"));
/* -------------------------------------------------------------------------- */

function createRecyclerViewAdapter(items) {
  let itemLayout = (
    <horizontal gravity="center_vertical" marginBottom="16">
      <View id="side" h="*" w="10" />
      <text id="content" marginLeft="16" textSize="16sp" textColor="#ffffff"></text>;
    </horizontal>
  );
  return RecyclerView.Adapter({
    onCreateViewHolder: function (parent, viewType) {
      // log("onCreateViewHolder");
      // 视图创建
      let view;
      let holder;
      view = ui.inflate(itemLayout, parent, false);
      holder = JavaAdapter(RecyclerView.ViewHolder, {}, view);
      view.click(function () {
        let item = items[holder.getAdapterPosition()];
        if (item.repoUrl) {
          // https://gitee.com/yashujs/Gitee.VisualStudio
          // 提取owner
          let reg = /gitee.com\/(.*)\/(.*)/;
          let match = item.repoUrl.match(reg);
          if (match) {
            let owner = match[1];
            let repo = match[2];
            let token = config.storage.get("token", false);
            let url = "https://gitee.com/api/v5/repos/" + owner + "/" + repo + "/branches/master?access_token=" + token;
            http.get(url, {}, function (res, err) {
              if (err) {
                console.error(err);
                return;
              }
              if (res.statusCode == 404) {
                toastLog("仓库不存在");
              } else {
                toastLog("仓库存在");

                engines.execScriptFile("page/repo-detail.js", { arguments: { repoUrl: item.repoUrl } });
              }
            });
          }
        }
      });
      return holder;
    },
    onBindViewHolder: function (holder, position) {
      // 数据绑定
      // 数据绑定
      let item = items[position];
      let view = holder.itemView;
      view.content.setText("" + item.full_name);
      view.side.setBackgroundColor(item.color);
    },

    getItemCount: function () {
      return items.length;
    },
  });
}
